package com.birdboot.controller;

import com.birdboot.core.DispatcherServlet;
import com.birdboot.entity.User;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;

/**
 *  V13新增内容
 *  处理用户相关业务的类
 */
public class UserController {

    //用于表示存储所有用户文件的users目录
    private static File userDir;

    static{
        userDir = new File("./users");
        if(!userDir.exists()){
            userDir.mkdirs();
        }
    }

    /**
     * 处理用户注册
     * @param request
     * @param response
     */
    public void reg(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户注册!!!!!!!");
        /*
                1通过request获取表单数据
                2将用户信息以User对象表示,并序列化到文件中
                3设置响应对象让浏览器查看处理结果页面
         */
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);

        //必要的验证
        if(username==null||username.isEmpty()||
                password==null||password.isEmpty()||
                nickname==null||nickname.isEmpty()||
                ageStr==null||ageStr.isEmpty()||!ageStr.matches("[0-9]{1,3}")
        ){
            response.sendRedirect("/reg_info_error.html");
            return;
        }
        File file = new File(userDir,username+".obj");
        if(file.exists()){
            response.sendRedirect("/have_user.html");
            return;
        }
        int age = Integer.parseInt(ageStr);//年龄要转换为整数
        User user = new User(username,password,nickname,age);
        try (
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
        ){
            oos.writeObject(user);
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
